import { Button, message, TypographyText, Upload } from 'ant-design-vue'
import { defineComponent, ref } from 'vue'
import * as xlsx from 'xlsx'

import { readFile } from '@/utils'

export default defineComponent({
  name: 'ImportPhoneList',
  props: {
    phones: {
      type: [Array],
      required: true,
      default: () => {
        return []
      }
    }
  },
  emits: ['update:phones'],
  setup(props, { emit }) {
    const phoneList = ref(props.phones as string[])

    /** 上传 */
    async function handleUploadData(file) {
      const fileData = await readFile(file.file)
      const listData = xlsx.read(fileData, { type: 'binary' })
      const reader = xlsx.utils.sheet_to_json(
        listData.Sheets[listData.SheetNames[0]]
      ) as any[]
      phoneList.value = []
      for (const item of reader) {
        if (item['手机号']) {
          phoneList.value.push(item['手机号'])
        }
      }
      if (phoneList.value.length == 0) {
        message.error('导入失败，请确定是否有“手机号”字段')
      }
      emit('update:phones', phoneList.value)
    }

    return {
      phoneList,
      handleUploadData
    }
  },
  render() {
    return (
      <div>
        <Upload
          accept=".xlsx,.xls"
          name="file"
          customRequest={this.handleUploadData}
          showUploadList={false}
        >
          <Button type="primary">导入手机号</Button>
        </Upload>
        <div>
          <TypographyText type="success" v-show={this.phoneList.length > 0}>
            {`导入成功，共${this.phoneList.length}条`}
          </TypographyText>
        </div>
      </div>
    )
  }
})
